package com.imax.center.tcp;

import java.io.*;
import java.net.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;

public class TCPClientTest {

    private static String serverAddress = "127.0.0.1";
    private static int port = 9000;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("按回车键开始循环发送数据，输入 'exit' 退出...");
        String input = scanner.nextLine();
        
        if ("exit".equalsIgnoreCase(input)) {
            System.out.println("客户端退出。");
            scanner.close();
            return;
        }

        DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

        // 使用注释中的message格式作为模板
        String messageTemplate = "##0299QN=20250707230010375;ST=32;CN=2051;PW=123456;MN=915301006KMTR1;Flag=4;CP=&&DataTime=20250707230000;w01001-Min=7.0541,w01001-Avg=7.0687,w01001-Max=7.0722,w01001-Cou=7.0687,w01001-Flag=N;w00000-Min=0.08,w00000-Avg=0.09,w00000-Max=0.09,w00000-Cou=0.01,w00000-ST=0.00,w00000-End=22741.00,w00000-Flag=N&&E681";
        
        int messageCount = 0;
        
        while (true) {
            messageCount++;
            
            // 生成带序号的消息
            String message = messageTemplate.replace("20250707230000", LocalDateTime.now().format(DATE_TIME_FORMATTER));
            
            try (Socket socket = new Socket(serverAddress, port);
                 PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {

                // 发送报文
                out.println(message);
                System.out.println("Client send [" + messageCount + "]: " + message);

                // 接收响应
                String response = in.readLine();
                System.out.println("Server response [" + messageCount + "]: " + response);

            } catch (UnknownHostException e) {
                System.err.println("Unknown host: " + serverAddress);
                break;
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
                break;
            }
            
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                System.err.println("Sleep interrupted: " + e.getMessage());
                break;
            }
        }

        scanner.close();
    }
}